package cn.edu.jxau.test;

import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

public class Main {

	public static void main(String[] args) {
		ListNode a = new ListNode(0);
		a.append(1).append(1);
		ListNode b = new ListNode(0);
		ListNode cur = plusAB(a, b);
		while (cur != null) {
			System.out.print(cur.val + " ");
			cur = cur.next;
		}
	}

	public static ListNode plusAB(ListNode a, ListNode b) {

		ListNode curA = a;
		ListNode curB = b;
		ListNode cur = null;
		ListNode result = null;
		boolean carry = false;
		while (curA != null && curB != null) {
			if (result == null) {
				int val = curA.val + curB.val;
				if (val >= 10) {
					carry = true;
				}
				cur = new ListNode(val % 10);
				result = cur;
			} else {
				int val = carry ? curA.val + curB.val + 1 : curA.val + curB.val;

				if (val >= 10) {
					carry = true;
				} else {
					carry = false;
				}
				cur.next = new ListNode(val % 10);
				cur = cur.next;
			}
			curA = curA.next;
			curB = curB.next;
		}
		while (curA != null) {
			int val = carry ? curA.val + 1 : curA.val;
			if (val >= 10) {
				carry = true;
			} else {
				carry = false;
			}
			cur.next = new ListNode(val % 10);
			cur = cur.next;
			curA = curA.next;
		}
		while (curB != null) {
			int val = carry ? curB.val + 1 : curB.val;
			if (val >= 10) {
				carry = true;
			} else {
				carry = false;
			}
			cur.next = new ListNode(val % 10);
			cur = cur.next;
			curB = curB.next;
		}
		if (carry) {
			cur.next = new ListNode(1);
		}
		return result;
	}
}

class ListNode {
	public int val;
	public ListNode next;

	ListNode(int val) {
		this.val = val;
	}

	public ListNode append(int val) {

		ListNode node = new ListNode(val);
		node.next = this.next;
		this.next = node;
		return node;
	}
}
